var Calendar = {};
Calendar.defaultEventColor = Config.defaultEventColor;

$(document).ready(function() {
  $('#error_message').hide();

	var applyToObject = function(event, result) {
		event.start 		= result.start;
		event.end 			= result.end;
		event._start 		= result.start;
		event._end 			= result.end;
		event._id 			= result.id;
		event.time_start= result.time_start;
		event.time_end  = result.time_end;
		event.color		  = result.color;
		event.allDay		= result.allDay;

    return event;
	};
// Timepicker Starttime
	$('#timepicker_starttime').timepicker({
		showPeriodLabels: false,
		hourText: Lang.Popup.TimepickerHourtext,
		minuteText: Lang.Popup.TimepickerMinutetext,
		showCloseButton: true,// shows an OK button to confirm the edit
		closeButtonText: Lang.Popup.TimepickercloseButtonText,// Text for the confirmation button (ok button)
		showNowButton: true,// Shows the 'now' button
		nowButtonText: Lang.Popup.TimepickernowButtonText,
		hours: {
			starts: Config.Popup.timePickerMinHour,
			ends: Config.Popup.timePickerMaxHour
		},
		minutes: {
			starts: 0,// First displayed minute
			ends: 59,// Last displayed minute
			interval: Config.Popup.timePickerMinuteInterval// Interval of displayed minutes
		}
	});
// Timepicker Endtime		
	$('#timepicker_endtime').timepicker({
		showPeriodLabels: false,
		hourText: Lang.Popup.TimepickerHourtext,
		minuteText: Lang.Popup.TimepickerMinutetext,
		showCloseButton: true,// shows an OK button to confirm the edit
		closeButtonText: Lang.Popup.TimepickercloseButtonText,// Text for the confirmation button (ok button)
		showNowButton: true,// Shows the 'now' button
		nowButtonText: Lang.Popup.TimepickernowButtonText,
		hours: {
		  starts: Config.Popup.timePickerMinHour,// First displayed hour
		  ends: Config.Popup.timePickerMaxHour// Last displayed hour
		},
		minutes: {
		  starts: 0,// First displayed minute
		  ends: 59,// Last displayed minute
		  interval: Config.Popup.timePickerMinuteInterval// Interval of displayed minutes
		}
	});
// Datepicker startdate
	$('#datepicker_startdate').datepicker({
		dateFormat: 'dd/mm/yy'
	});
// Datepicker enddate
	$('#datepicker_enddate').datepicker({
		dateFormat: 'dd/mm/yy'
	});
// Colorpicker
	$('#ColorPicker1').empty().addColorPicker({
		clickCallback: function(elem,c) {
			$('#ColorSelectionTarget1').css('background-color',c);
			Calendar.defaultEventColor = elem.attr('color');
		}
	});
	$('#ColorSelectionTarget1').css('background-color',Calendar.defaultEventColor);
//#########################
	var disableTimeCombos = function() {
		$('#timepicker_starttime').attr('disabled', 'disabled');
		$('#timepicker_endtime').attr('disabled', 'disabled');
	};
	var enableTimeCombos = function() {
		$('#timepicker_starttime').removeAttr('disabled');
		$('#timepicker_endtime').removeAttr('disabled');
	};
	$('#allday_checkbox').click(function(t){
		if(t.currentTarget.checked == false) {
			$('#timepicker_starttime').removeAttr('disabled');
			$('#timepicker_endtime').removeAttr('disabled');
		}else{
			$('#timepicker_starttime').attr('disabled', 'disabled');
			$('#timepicker_endtime').attr('disabled', 'disabled');
		}
	});
//#########################
		
		
// START Add new Event (click on empty Date Field)		
	var addEvent = function(start, end) {
		$('#error_message').hide();
		var title = $('#edited_title')[0].value;
		if (title) {
      // is a date selected in the datepickers, then use those dates
			var dp_startdate 	= $('#datepicker_startdate').datepicker('getDate');
			var dp_enddate 		= $('#datepicker_enddate').datepicker('getDate');

			if(dp_startdate !== null && dp_enddate !== null) {
				start = dp_startdate;
				end = dp_enddate;
			}
				
			if($('#allday_checkbox').is(':checked')) {
				var startdate = Date.parse(start) / 1000;
				var enddate = Date.parse(end) / 1000;
			}else{
				var startdate 	= Date.parse(start.format('mm/dd/yyyy')+ ' ' + $('#timepicker_starttime')[0].value + ':00') / 1000;
				var enddate 	  = Date.parse(end.format('mm/dd/yyyy')+ ' ' + $('#timepicker_endtime')[0].value + ':00') / 1000;
			}
			var note

			if(startdate <= enddate  && dp_startdate !== null && dp_enddate !== null) {
			 // insert to DB
				var dataString = 'title='+ title +'&date_start='+ startdate + '&date_end='+ enddate + '&color=' + Calendar.defaultEventColor;
				$.ajax({
					type:"POST",
					url:"command/cal_events.php?action=add",
					data: dataString,
					success:function(result){
						result.event._id = result.event.id;
					}
				});
				$('#calendar').fullCalendar('refetchEvents');
			}else{
				$('#error_message').html(Lang.Alert.TimesNotCorrect);			    
				$('#error_message').show();
			}
		}
	};
// END Add new Event (click on empty Date Field)

// START Update existing Event (click on existing Event and made some Changes)
	var updateEvent = function(event) {
		$('#error_message').hide();

		var title = $('#edited_title')[0].value;
		if(title != null && title != '') {
			event.title = title;
        
      // is a date selected in the datepickers, then use those dates
			var dp_startdate 	= $('#datepicker_startdate').datepicker('getDate');
			var dp_enddate 		= $('#datepicker_enddate').datepicker('getDate');

			if(dp_startdate !== null && dp_enddate !== null) {
				event.start = dp_startdate;
				event.end = dp_enddate;
			}
				
			if($('#allday_checkbox').is(':checked')) {
				var startdate = Date.parse(event.start) / 1000;
				var enddate = event.end !== null ? Date.parse(event.end) / 1000 : startdate;
				event.allDay = 1;
			}else{
				var startdate 	= Date.parse(event.start.format('mm/dd/yyyy')+ ' ' + $('#timepicker_starttime')[0].value + ':00') / 1000;
			  var enddate 	= Date.parse(event.start.format('mm/dd/yyyy')+ ' ' + $('#timepicker_endtime')[0].value + ':00') / 1000;
				event.allDay = 0;
			}

			if(startdate <= enddate && dp_startdate !== null && dp_enddate !== null ) {
				// update DB
				var dataString = 'event_id='+ event.event_id + '&allDay=' + event.allDay  + '&title='+ event.title + '&date_start='+startdate+'&date_end='+enddate+ '&color=' + Calendar.defaultEventColor;
        $.ajax({
          type:"POST",
			    url:"command/cal_events.php?action=update",
			    data: dataString,
					success:function(result){
					 event = applyToObject(event, result.event);
			    }
			  });

			  $('#calendar').fullCalendar('refetchEvents');
			  return true;
			}else{       
				$('#error_message').html(Lang.Alert.TimesNotCorrect);			    
			  $('#error_message').show();
			  return false;
			}
    }
	};
// END Update existing Event (click on existing Event and made some Changes)

// START update existing Event when User moved it (drag'n'drop)
	var onEventDropEvent = function(event) {
		$('#error_message').hide();
		var startdate 	= Date.parse(event.start) / 1000;
		if(event.end === null) {
	    var enddate = startdate;
	  }else{
	    var enddate 	= Date.parse(event.end) / 1000;
	  }
    event.allDay = event.allDay ? 1 : 0;

    // opslaan in db
		var dataString = 'event_id='+event.id + '&color=' + event.color + '&allDay=' + event.allDay +'&title='+ event.title+'&date_start='+startdate+'&date_end='+enddate;
    $.ajax({
	   type:"POST",
	   url:"command/cal_events.php?action=update",
	   data: dataString
			});
	};
// END update existing Event when User moved it (drag'n'drop)		
		
	var onSelectEvent = function(start, end, allDay) {
		$('#error_message').hide();
		$('#dialog:ui-dialog').dialog( "destroy" );
		$('#edited_title')[0].value = '';
		$('#datepicker_startdate').datepicker('setDate', start); 
		$('#datepicker_enddate').datepicker('setDate', end);
		// default
		$('#allday_checkbox').attr('checked', false);

		$('#wholeday_label_id').html(Lang.Popup.allDayLabel);
		$('#month_label_id').html(Lang.Popup.MonthLabel );
		$('#time_label_id').html(Lang.Popup.TimeLabel );

		$('#calendar').fullCalendar('unselect');
		
		enableTimeCombos();
			
		var curr_hour = start.getHours();
		var curr_min = start.getMinutes();

		if(curr_hour == 0 && curr_min == 0) {
			var now = new Date();
			$('#timepicker_starttime')[0].value = dateFormat(now,'HH:00');
			$('#timepicker_endtime')[0].value	= dateFormat(now,'HH:00');
		}else{
			$('#timepicker_starttime')[0].value = dateFormat(start,'HH:MM');
			$('#timepicker_endtime')[0].value 	= dateFormat(end,'HH:MM');
		}

		$('#dialog-message').dialog({
			modal: true,
			title: Lang.Popup.Title,
			height: 400,
			width: 285,
			buttons: [{
			  text: Lang.Popup.saveButtonText,
			  click: function (a,b) {
			    var title = $('#edited_title')[0].value;
					 if(title != null && title != '') {
						$( this ).dialog( "close" );
						addEvent(start, end);
					 }else{
					  $('#error_message').html(Lang.Alert.EventTitleRequired);			    
			      $('#error_message').show();						
					}
			  }
			},
      {
			  text: Lang.Popup.closeButtonText,
			  click: function () {
			    $( this ).dialog( "close" );
			  }
			}]
		});
	};

	var onMouseoverEvent = function(me, event) {
		if(event.editable) {
			/*
			*	SHOW DELETE ICON, ALSO POSSIBLE TO SHOW AN EDIT ICON HERE
			*/
			var layer =	'<div id="events-layer" class="fc-transparent" style="position:absolute; width:100%; height:100%; top:-1px; text-align:right; z-index:100">'
			+ '<a><img src="images/delete.png" title="delete" width="14" id="delbut'+event.id+'" border="0" style="padding-right:5px; padding-top:2px;" /></a>'
			+ '</div>';

			me.append(layer);
			$('#delbut'+event.id).hide();
			$('#delbut'+event.id).fadeIn(200);
			$('#delbut'+event.id).click(function() {
				if(event.id) {
					// opslaan in db
					var dataString = 'event_id='+ event.id ;
			    $.ajax({
				    type:"POST",
				    url:"command/cal_events.php?action=del",
				    data: dataString,
				    success:function(html){}
				  });
					$('#calendar').fullCalendar('removeEvents', event.id);
				}
			});
		}
	};

	var onClickEvent = function(event) {
		$('#error_message').hide();
		if(!event.editable) {
			$('#error_message').html(Lang.Alert.NotAllowedToEdit);			    
			$('#error_message').show();			
		}else{
			var startdate = event.start;
			if(event.end === null) {
				var enddate = startdate;
			}else{
				var enddate = event.end
			}
	            
		  $( "#dialog:ui-dialog" ).dialog( "destroy" );
		  $('#edited_title')[0].value = event.title;

		  $( "#datepicker_startdate" ).datepicker('setDate', dateFormat(Date.parse(startdate),'dd/mm/yy')); // or dateFormat(event._start,'dd/mm/yyyy')
		  $( "#datepicker_enddate" ).datepicker('setDate', dateFormat(Date.parse(enddate),'dd/mm/yy'));

		  $('#timepicker_starttime')[0].value = event.time_start.substring(0,5);
		  $('#timepicker_endtime')[0].value = event.time_end.substring(0,5);

		  if(event.allDay ) {
				$('#allday_checkbox').attr('checked', true);
				disableTimeCombos();
			}else{
				$('#allday_checkbox').attr('checked', false);
				enableTimeCombos();
			}
		if(event.color === '') {
				event.color = Calendar.defaultEventColor;
			}
			$('#ColorSelectionTarget1').css('background-color',event.color);
			Calendar.defaultEventColor = event.color;

			$( "#dialog-message" ).dialog({
				modal: true,
				title: Lang.Popup.Title,
				height: 400,
				width: 285,
				buttons: [{
					text: Lang.Popup.updateButtonText,
					click: function () {
				    var title = $('#edited_title')[0].value;	    
						if(title != null && title != '') {
							var bln_correct = updateEvent(event);
								if(bln_correct) {
								$( this ).dialog( "close" );
								$('#error_message').html('');
							}
						}else{
							$('#error_message').html(Lang.Alert.EventTitleRequired);			    
							$('#error_message').show();
						}
					}
				},
				{
					text: Lang.Popup.closeButtonText,
					click: function () {
						$( this ).dialog( "close" );
					}
				}]
			});
			
			$('#wholeday_label_id').html(Lang.Popup.allDayLabel);
			$('#month_label_id').html(Lang.Popup.MonthLabel );
			$('#time_label_id').html(Lang.Popup.TimeLabel );
		}
	};

		/* initialize the external events
		-----------------------------------------------------------------*/

		$('#external-events div.external-event').each(function() {

			// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
			// it doesn't need to have a start or end
			var eventObject = {
				title: $.trim($(this).text()) // use the element's text as the event title
			};

			// store the Event Object in the DOM element so we can get to it later
			$(this).data('eventObject', eventObject);

			// make the event draggable using jQuery UI
			$(this).draggable({
				zIndex: 999,
				revert: true,      // will cause the event to go back to its
				revertDuration: 0  //  original position after the drag
			});

		});

		/* initialize the calendar
		-----------------------------------------------------------------*/

		
});
